-- homesounds.lua

local m = {}
m.version = "1.0"

local content_root = ".\\content\\CrowdSoundOverhaul\\"
local tmap
local debug = true

local function load_map(filename)
    local map = {}
    for line in io.lines(filename) do
        -- strip comment
        line = string.gsub(line, "#.*", "")
        local tid, path = string.match(line, "%s*(%d+)%s*,%s*[\"]?([^\"]*)")
        tid = tonumber(tid)
        if tid and path then
            map[tid] = path
            log(string.format("tid: %d ==> content path: %s", tid, path))
        end
    end
    return map
end

local function file_exists(pathname)
    --log(string.format("checking: %s", pathname))
    local f = io.open(pathname)
    if f then
        f:close()
        return true
    end
end

function m.get_filepath(ctx, filename)
    local team_root = tmap[ctx.home_team]
    if team_root then
        local pathname = string.format("%s%s\\%s", content_root, team_root, filename)
        -- not necessary for normal workflow, but just for debugging purposes
        -- we can check for file existence here and log it, if we have the file.
        -- During regular playing it's best to set debug to false and let the
        -- the sider's livecpk engine do the checking of file existence.
        if debug and file_exists(pathname) then
            log(string.format("serving: %s", pathname))
        end
        return pathname
    end
end

function m.init(ctx)
    if content_root:sub(1,1) == "." then
        content_root = ctx.sider_dir .. content_root
    end
    tmap = load_map(content_root .. "map.txt")
    ctx.register("livecpk_get_filepath", m.get_filepath)
end

return m
